<template>
  <a-modal
    title="物料选择"
    width="85vw"
    :visible="innerVisible"
    dialogClass="zero-modal"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-spin :spinning="loading">
      <div class="ex-warehouse1-choose-modal-content">
        <div class="choose-bar">
          <div class="choose-form-view">
            <a-form layout="inline">
              <a-row>
                <a-col :md="8" :sm="24">
                  <a-form-item label="托盘编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model.trim="query.ContainerCode" placeholder="请输入..." allowClear />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select style="width: 100%" v-model="query.MaterialType" placeholder="请选择..." allowClear>
                      <a-select-option v-for="(item,index) in types" :value="item.code" :key="'types-sel-'+index">{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model.trim="query.MaterialName" placeholder="请输入..." allowClear />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model.trim="query.Specifications" placeholder="请输入..." allowClear />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="批次" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model.trim="query.MaterialBatch" placeholder="请输入..." allowClear />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="密度" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model.trim="query.Density" placeholder="请输入..." allowClear />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div class="choose-btns-view">
            <a-button type="primary" style="margin-bottom:6px;" @click.stop="onQuery">查询</a-button>
            <a-button @click.stop="onReset">重置</a-button>
          </div>
        </div>
        <div class="table-box" ref="listWrapper">
          <div class="action-view" v-if="showType===1">
            <a-table v-if="th1" :data-source="list" :columns="listColumns" 
              :pagination="{current:queried.PageNo,pageSize:queried.PageSize,total:listTotal}" 
              rowKey="id" :row-selection="{onChange:rowSelectionsChange,selectedRowKeys:selectedRowKeys}" :scroll="{x:1300,y:th1}"
              @change="chooseTablePageChange">
              <template slot="index" slot-scope="text,record,index">{{(queried.PageNo-1)*queried.PageSize+(index+1)}}</template>
            </a-table>
          </div>
          <div class="choosen-view" v-else>
            <a-table v-if="th2" :data-source="choosen" :columns="choosenColumns" rowKey="id" :pagination="false" :scroll="{x:1300,y:th2}">
              <template slot="action" slot-scope="text,record,index">
                <a-button type="danger" size="small" @click.stop="cancelChoosen(index)">删除</a-button>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="choosen" type="primary" @click="changeShowType">所选物料<span v-if="choosen.length>0">({{choosen.length}})</span></a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleSubmit" :disabled="!choosen.length">确认</a-button>
    </template>
  </a-modal>
</template>

<script>
import { QueryMaterials } from '@/api/modular/main/ExWarehouseManage1'
const defaultQuery = {
  MaterialType:undefined,
  MaterialName:'',
  Specifications:'',
  MaterialBatch:'',
  Density:'',
  ContainerCode:''
}
const pagination = {
  PageNo:1,
  PageSize:10
} 
export default {
  emits:['update:visible','callback'],
  props:{
    visible:{
      type:Boolean,
      default:false
    }
  },
  data(){
    return {
      innerVisible:false,
      loading:false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      types:[],
      query:{...defaultQuery},
      queried:{...pagination},
      listTotal:0,
      list:[],
      listColumns:[
        { title: '序号', key: 'index', width: 70, align:'center', fixed:"left", scopedSlots: { customRender: 'index' }},
        { title: '物料编码', dataIndex: 'materialNo', key: 'materialNo', width: 150 },
        { title: '图号', dataIndex: 'drawingNo', key: 'drawingNo' },
        { title: '尺寸', dataIndex: 'materialSpec', key: 'materialSpec', width: 150 },
        { title: '库区', dataIndex: 'areaName', key: 'areaName', width: 120 },
        { title: '库位', dataIndex: 'placeCode', key: 'placeCode', width: 150 },
        { title: '托盘号', dataIndex: 'containerCode', key: 'containerCode', width: 120 },
        { title: '数量', dataIndex: 'stockNumber', key: 'stockNumber', width: 100 }
      ],
      selectedRowKeys:[],
      choosen:[],
      choosenColumns:[
        { title: '物料编码', dataIndex: 'materialNo', key: 'materialNo', width: 150 },
        { title: '图号', dataIndex: 'drawingNo', key: 'drawingNo' },
        { title: '尺寸', dataIndex: 'materialSpec', key: 'materialSpec', width: 150 },
        { title: '库区', dataIndex: 'areaName', key: 'areaName', width: 120 },
        { title: '库位', dataIndex: 'placeCode', key: 'placeCode', width: 150 },
        { title: '托盘号', dataIndex: 'containerCode', key: 'containerCode', width: 120 },
        { title: '操作', key: 'action', width: 80, align:'center', fixed:"right", scopedSlots: { customRender: 'action' }}
      ],
      showType:1,   //1显示查询页面； 2显示已选数据
      th1:0,
      th2:0
    }
  },
  created(){
    this.innerVisible = this.visible
    this.types = this.$options.filters['dictData']('material_type')
  },
  watch:{
    visible(newVal){
      if (newVal!==this.innerVisible) {
        this.innerVisible = newVal
      }
    },
    innerVisible(newVal,oldVal){
      if (newVal!==this.visible) {
        this.$emit('update:visible',newVal)
      }
      if (newVal!==oldVal) {
        if (newVal) {
          this.init()
        }
      }
    }
  },
  methods:{
    init(){
      this.$nextTick(() => {
        let h = this.$refs.listWrapper.clientHeight
        this.th1 = h - 120
        this.th2= h - 60
        this.resetQuery()
      });
    },
    handleSubmit(){
      this.$emit('callback',this.choosen)
      this.handleCancel()
    },
    handleCancel(){
      this.innerVisible = false;
      this.showType = 1
      this.list = []
      this.choosen = []
      this.loading = false
      this.query = {...defaultQuery}
      this.queried = {...pagination}
    },
    onQuery(){
      this.newQuery()
    },
    onReset(){
      this.resetQuery()
    },
    resetQuery(){
      this.query = {...defaultQuery}
      this.newQuery()
    },
    newQuery(){
      this.queried = {...this.query,...pagination}
      this.queryChooseDataSource()
    },
    queryChooseDataSource(){
      this.loading = true;
      QueryMaterials(this.queried).then((d)=>{
        this.list = d.data.rows || []
        this.listTotal = d.data.totalRows || 0
        this.setSelectedRowKeys()
        this.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },
    rowSelectionsChange(selectedRowKeys, selectedRows){
      let reduces = [], adds = []
      /* 计算需要被移出choosen的内容 */
      this.selectedRowKeys.forEach((val)=>{
        let f1 = false;
        for (let i=0;i<selectedRowKeys.length;i++) {
          if (selectedRowKeys[i] === val) {
            f1 = true;
            break;
          }
        }
        if (!f1) {
          reduces.push(val)
        }
      })
      /* 计算需要被加入choosen的内容 */
      selectedRowKeys.forEach((val)=>{
        let f2 = false;
        for (let i=0;i<this.choosen.length;i++) {
          if (this.choosen[i].id === val) {
            f2 = true;
            break;
          }
        }
        if (!f2) {
          adds.push(val)
        }
      })
      /* 执行实际数据处理，先减后加，减少处理时间 */
      this.selectedRowKeys = selectedRowKeys
      this.reduceChoosen(reduces)
      this.addChosen(adds)
    },
    chooseTablePageChange(pagination){
      this.queried.PageNo = pagination.current
      this.queryChooseDataSource()
    },
    reduceChoosen(arr){
      arr.forEach((val)=>{
        let reduceIndex = -1;
        for (let i=0;this.choosen.length;i++) {
          if (this.choosen[i].id === val) {
            reduceIndex = i
            break;
          }
        }
        if (reduceIndex>=0) {
          this.choosen.splice(reduceIndex,1)
        }
      })
    },
    cancelChoosen(index){
      this.choosen.splice(index,1)
    },
    addChosen(arr){
      arr.forEach((val)=>{
        for (let i=0;this.list.length;i++) {
          if (this.list[i].id === val) {
            let obj = {...this.list[i]}
            this.choosen.push(obj)
            break;
          }
        }
      })
    },
    setSelectedRowKeys(){
      let arr = []
      this.choosen.forEach((item)=>{
        for (let i=0;i<this.list.length;i++) {
          if (this.list[i].id === item.id) {
            arr.push(item.id)
            break;
          }
        }
      })
      this.selectedRowKeys = arr
    },
    changeShowType(){
      if (this.showType===1) {
        this.showType = 2
      } else {
        this.showType = 1
        this.setSelectedRowKeys()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ex-warehouse1-choose-modal-content{
  height: 70vh;
  display: flex;
  flex-direction: column;
  .choose-bar{
    flex-shrink: 0;
    padding: 8px 4px;
    display: flex;
    .choose-form-view{
      flex-grow: 1;
    }
    .choose-btns-view{
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
  }
  .table-box{
    flex-grow: 1;
    padding: 0 16px;
    overflow: auto;
  }
  .ant-form-inline{
    .ant-form-item {
      margin-right: 0;
      width: 100%;
    }
  } 
}
</style>